import React, { Component } from 'react';
import {
  G2,
  Chart,
  Geom,
  Axis,
  Tooltip,
  Coord,
  Label,
  Legend,
  View,
  Guide,
  Shape,
  Facet,
  Util
} from "bizcharts";


export default class LineChart extends Component {
  static displayName = 'LineChart';

  constructor() {
    super();
    this.state = {
      size: 20,
      data: []
    };
  }

  componentDidMount() {
    this.setState({data:this.props.data})
  }

  componentWillReceiveProps(nextProps) {
    const nextData = nextProps.data;
    const type = Object.prototype.toString.call(nextData);
    let data = [...this.state.data]
    if("[object Array]" === type) {
      data = [...this.state.data, ...nextData];
    } else if("[object Object]" === type) {
      data = [...this.state.data, nextData];
    }

    data = data.slice(data.length > this.state.size ? data.length-this.state.size : 0, data.length)
    this.setState({data})
  }

  onPlotDblClick(ev) {
    if(this.props.onPlotDblClick) {
      this.props.onPlotDblClick();
    }
  }

  render() {
    const cols = {
      xAxis: {
        range: [0, 1]
      }
    };
    const background = {
      fill: '#ffffff', // 图表背景色-白色
    };
    const xAxis = this.props.xAxis ? this.props.xAxis : 'xAxis';
    const yAxis = this.props.yAxis ? this.props.yAxis : 'yAxis';
    const color = this.props.color ? this.props.color : 'field';
    const position = xAxis + "*" + yAxis;
    return (
      <div>
        <Chart 
          placeholder 
          onPlotDblClick={this.onPlotDblClick.bind(this)} 
          height={this.props.height} 
          data={this.state.data} 
          scale={cols} 
          background={background}
          forceFit>
            <Legend visible={!!this.props.legendVisible} />
            <Axis name={xAxis} visible={!!this.props.xAxisVisible} />
            <Axis name={yAxis} />
            <Tooltip
              crosshairs={{
                type: yAxis
              }}
            />
            <Geom
              type="line"
              position={position}
              size={1}
              color={color}
              shape={"smooth"}
            />
            <Geom
              type="point"
              position={position}
              size={2}
              shape={"circle"}
              color={color}
              style={{
                stroke: "#fff",
                lineWidth: 1
              }}
            />
        </Chart>
      </div>
    );
  }
}